//
//  GenerateQRCardController.m
//  QRMaster
//
//  Created by myApple on 16/6/2.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "GenerateQRCardController.h"
#import "GenerateQRCardView.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "shareDimensionalView.h"
#import "ZXMultiFormatWriter.h"
#import "ZXImage.h"
#import "ZXingObjC.h"
#import <ShareSDK/ShareSDK.h>
#import "DropDownMenuView.h"
#import <AudioToolbox/AudioToolbox.h>
#import "OpertionPlist.h"
#import "anaylsistDimensional.h"
#import "EditShareTimeViewController.h"
#import "StartPageController.h"
#import "setTimeModel.h"
#import "RoomTimeView.h"
#import "InternationalControl.h"
#import "ShareUIView.h"
#import <MessageUI/MessageUI.h>
#import "CardInfoModel.h"
#import "AddBackViewCell.h"
#import "QuickCardProcess.h"
#import "QuickCardModel.h"
#import "RoomTimeView.h"
#import "GenerateCardHelpView.h"
#import "ShareTimeEditVC.h"
@interface GenerateQRCardController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,GenerateQRCardViewDelegate>
{
    GenerateQRCardView * qrCardView;
    anaylsistDimensional * anaylsistDim;
    NSArray * imageArray;
    NSArray * imageTitleArray;
    CGFloat value;//刚进页面的亮度
    UIView * backView;//白色遮罩层
    UIButton * addBtn;
    BOOL cardIsCollect;
    QuickCardProcess * cardProcess;
    UIView * timeAndPromtBackView;
    RoomTimeView * timeView;
    GenerateCardHelpView * helpView;
    NSInteger currentIndex;//当前收藏房间的序号
}

@property(nonatomic,strong)CardInfoModel * CardModel;

@property(nonatomic,strong)QuickCardModel * collectCardModel;

@property(nonatomic,strong)UITableView * backTableView;

@end

static SystemSoundID shake_sound_male_id = 0;

static SystemSoundID shake_sound_refresh = 1;

@implementation GenerateQRCardController

-(id)initWithCardModel:(CardInfoModel *)model
{
    if (self) {
        // Custom initialization
        self.CardModel = model;
       cardProcess = [[QuickCardProcess alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"Card", nil);
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [self prepareNavView];
    [self prepareQRCardView];
    [self getCard];
    [self checkCardIsCollect];
    [self prepareTimeView];
    currentIndex = 10;//默认当前序号是没有的（1到5）
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    value = [UIScreen mainScreen].brightness;
    addBtn.hidden = NO;
    [[UIScreen mainScreen]setBrightness:1.0];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    addBtn.hidden = YES;
    [[UIScreen mainScreen] setBrightness:value];
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

#pragma mark - 看看当前卡是否是收藏的房卡
-(void)checkCardIsCollect
{
    __weak GenerateQRCardController * weakSelf = self;
    [cardProcess getCollectFromDBBlock:^(NSArray *collectCardArray) {
        NSInteger i = 0;
        NSInteger count = collectCardArray.count;
        for (i = 0; i < count; i ++) {
            QuickCardModel * collectModel = collectCardArray[i];
            if ([collectModel.roomId isEqualToString:weakSelf.CardModel.roomId]) {
                imageArray = @[@"cardShare",@"cardCollect",@"cardRefresh"];
                imageTitleArray = @[NSLocalizedString(@"cardShare", nil),NSLocalizedString(@"cancelCollect", nil),NSLocalizedString(@"cardRefresh", nil)];
                cardIsCollect = YES;
                weakSelf.collectCardModel = collectModel;
                currentIndex = collectModel.index;
                break;
            }
        }
        if (i >= count) {
            imageArray = @[@"cardShare",@"unCardCollect",@"cardRefresh"];
            imageTitleArray = @[NSLocalizedString(@"cardShare", nil),NSLocalizedString(@"cardCollect", nil),NSLocalizedString(@"cardRefresh", nil)];
            cardIsCollect = NO;
        }
        [weakSelf prepareMenu];
    }];
}

#pragma mark - 导航栏上面的加号
-(void)prepareNavView
{
    addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(UI_SCREEN_WIDTH - 48, 0, 48, 44);
    [addBtn addTarget:self action:@selector(addMenu) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:addBtn];
    
    UIImageView * addImgView = [[UIImageView alloc]initWithFrame:CGRectMake(16, 15, 16, 16)];
    addImgView.image = [UIImage imageNamed:@"cardAdd"];
    [addBtn addSubview:addImgView];
}

#pragma mark - 查看时间的显示
-(void)prepareTimeView
{
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = UI_SCREEN_WIDTH;
    CGFloat height = UI_SCREEN_HEIGHT - 64;
    timeAndPromtBackView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    timeAndPromtBackView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    timeAndPromtBackView.hidden = YES;
    [self.view addSubview:timeAndPromtBackView];
    
    UITapGestureRecognizer * backTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeBackView)];
    [timeAndPromtBackView addGestureRecognizer:backTap];
    
    x = width;
    y = timeAndPromtBackView.frame.size.height;
    height = 240;
    helpView = [[GenerateCardHelpView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    helpView.backgroundColor = [UIColor whiteColor];
    helpView.hidden = YES;
    [timeAndPromtBackView addSubview:helpView];
    
    timeView = [[RoomTimeView alloc]init];
    timeView.frame = helpView.frame;
    timeView.hidden = YES;
    timeView.backgroundColor = [UIColor whiteColor];
    [timeAndPromtBackView addSubview:timeView];
}

#pragma mark - 移除背景图
-(void)removeBackView
{
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = helpView.frame;
        frame.origin.y = timeAndPromtBackView.frame.size.height;
        frame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        helpView.frame = frame;
        CGRect timeFrame = timeView.frame;
        timeFrame.origin.y = timeAndPromtBackView.frame.size.height;
        timeFrame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        timeView.frame = timeFrame;
    } completion:^(BOOL finished) {
        timeAndPromtBackView.hidden = YES;
        helpView.hidden = YES;
        timeView.hidden = YES;
        helpView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, helpView.frame.origin.y, helpView.frame.size.width, helpView.frame.size.height);
        timeView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, helpView.frame.origin.y, helpView.frame.size.width, helpView.frame.size.height);
    }];
}

#pragma mark - 点击导航栏加号展出的菜单栏
-(void)prepareMenu
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT;
    backView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
    backView.userInteractionEnabled = YES;
    backView.hidden = YES;
    [self.view addSubview:backView];
    UITapGestureRecognizer * tapAllBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenBackView)];
    tapAllBackView.delegate = self;
    [backView addGestureRecognizer:tapAllBackView];
    
    x = backView.frame.size.width - 29;
    y = 4;
    width = 11;
    height = 6;
    UIImageView * triangleView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    triangleView.image = [UIImage imageNamed:@"triangle"];
    triangleView.backgroundColor = [UIColor clearColor];
    [backView addSubview:triangleView];
    
    x = UI_SCREEN_WIDTH - 134;
    y = 10;
    width = 128;
    height = 38 * 3;
    if ([[InternationalControl userLanguage]isEqualToString:@"en"]) {
        x = UI_SCREEN_WIDTH / 2.0 - 26;
        width = UI_SCREEN_WIDTH / 2.0 + 20;
    }
    _backTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    _backTableView.backgroundColor = [UIColor blackColor];
    _backTableView.layer.cornerRadius = 2;
    _backTableView.separatorStyle = UITableViewCellSeparatorStyleNone;;
    _backTableView.delegate = self;
    _backTableView.dataSource = self;
    _backTableView.tableFooterView = [UIView new];
    [backView addSubview:_backTableView];
}

-(void)addMenu
{
    if (backView.hidden) {
        [self showBackView];
    }
    else
    {
        [self hiddenBackView];
    }
}

-(void)showBackView
{
    backView.hidden = NO;
    backView.userInteractionEnabled = YES;
}

-(void)hiddenBackView
{
    backView.hidden = YES;
    backView.userInteractionEnabled = NO;
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark - PrepareView
-(void)prepareQRCardView
{
    CGFloat x = 0;
    CGFloat y = 16;
    CGFloat width = UI_SCREEN_WIDTH;
    CGFloat height = UI_SCREEN_HEIGHT - y;
    qrCardView = [[GenerateQRCardView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    qrCardView.buildName = self.CardModel.bulidingName;
    qrCardView.floorName = self.CardModel.floorName;
    qrCardView.roomName = self.CardModel.roomName;
    qrCardView.delegate = self;
    [self.view addSubview:qrCardView];
}

#pragma mark - generateQRCardViewDelegate
-(void)lookCardTime
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:self.CardModel.communityid forKey:@"communityId"];
    [postDict setValue:self.CardModel.roomId forKey:@"roomId"];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [rnk initWithPath:POST(GETMYSELFROOMTINE) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        NSDictionary * data = [downLoadData objectForKey:@"data"];
        if (data != nil) {
            if ([[data objectForKey:@"flag"]intValue] == 0) {
                NSMutableArray * timeDataArray = [[NSMutableArray alloc]init];
                NSArray * listArray = [data objectForKey:@"list"];
                for (NSDictionary * dict in listArray) {
                    setTimeModel * model = [[setTimeModel alloc]init];
                    model.beginTime = [dict objectForKey:@"startTime"];
                    model.endTime = [dict objectForKey:@"endTime"];
                    model.weekInfo = [dict objectForKey:@"cycleString"];
                    model.timeId = [dict objectForKey:@"id"];
                    [timeDataArray addObject:model];
                }
                if (timeDataArray.count == 0) {
                    [PromptInfoView showMessage:NSLocalizedString(@"noTimeOpenRoom", nil)];
                }
                else
                {
                    timeAndPromtBackView.hidden = NO;
                    timeView.hidden = NO;
                    [UIView animateWithDuration:0.5 animations:^{
                        CGRect frame = timeView.frame;
                        frame.origin.y = timeAndPromtBackView.frame.size.height - (timeDataArray.count * 55 + 80);
                        frame.origin.x = 0;
                        timeView.frame = frame;
                        timeView.timeData = timeDataArray;
                    } completion:^(BOOL finished) {
                        
                    }];
                }
            }
            else
            {
                [PromptInfoView showMessage:NSLocalizedString(@"managerOpenTime", nil)];
            }
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
            
        }
        
    }];

}

-(void)showHelpView
{
    timeAndPromtBackView.hidden = NO;
    helpView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = helpView.frame;
        frame.origin.y = timeAndPromtBackView.frame.size.height - 200;
        frame.origin.x = 0;
        helpView.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark  ---- 注册声音到系统
-(void)playSound
{
    NSString * path = [[NSBundle mainBundle]pathForResource:@"5018" ofType:@"wav"];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &shake_sound_male_id);
        AudioServicesPlayAlertSound(shake_sound_male_id);
    }
}

-(void)playRefreshSound
{
    NSString * path = [[NSBundle mainBundle]pathForResource:@"shake_match" ofType:@"mp3"];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &shake_sound_refresh);
        AudioServicesPlayAlertSound(shake_sound_refresh);
    }
}

-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    //播放声音
    [self playSound];
}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    [self getCard];
}

#pragma mark - 二维码生成
-(void)getCard
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:self.CardModel.communityid forKey:@"communityId"];
    [postDict setValue:self.CardModel.bulidingId forKey:@"buildingId"];
    [postDict setValue:self.CardModel.floorId forKey:@"floorId"];
    [postDict setValue:self.CardModel.roomId forKey:@"roomId"];
    [postDict setValue:@"0" forKey:@"validTime"];
    [postDict setValue:@"3" forKey:@"type"];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [self startWaiting:nil color:nil addToView:self.view];
    [rnk initWithPath:POST(CHECKAUTHORTIY) params:postDict block:^(id downLoadData, id error) {
            [self stopWaiting];
            [self downLoadDataHandel:downLoadData errorInfo:error];
        }];
}

-(void)downLoadDataHandel:(id)downLoadData errorInfo:(id)error
{
    NSDictionary * data = [downLoadData objectForKey:@"data"];
    if (data != nil) {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"sound"]isEqualToString:@"1"]) {
            [self playRefreshSound];
        }
        qrCardView.generateCardString = [data objectForKey:@"cardString"];
        
    }
    else if (error != nil) {
        qrCardView.generateCardString = nil;
        [PromptInfoView showMessage:[error objectForKey:@"info"]];
    }
    
}

#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return imageArray.count;
}

-(CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 38.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddBackViewCell * cell = [AddBackViewCell cellWithTableView:tableView];
    cell.backgroundColor = [UIColor blackColor];
    cell.title = imageTitleArray[indexPath.row];
    cell.imageNameString = imageArray[indexPath.row];
    cell.indexRow = indexPath.row;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self hiddenBackView];
    switch (indexPath.row) {
        case 0:
            [self share];
            break;
        case 1:
            if (cardIsCollect) {
                [self cancelCollectCard];
            }
            else
            {
                [self collectCard];
            }
            break;
        case 2:
            [self getCard];
            break;
        default:
            break;
    }
}

#pragma mark - share
-(void)share
{
//    EditShareTimeViewController * estvc = [[EditShareTimeViewController alloc]init];
    ShareTimeEditVC * estvc = [[ShareTimeEditVC alloc] init];
    estvc.communityId = self.CardModel.communityid;
    estvc.roomId = self.CardModel.roomId;
    [self.navigationController pushViewController:estvc animated:YES];
}

#pragma mark - 收藏房卡
-(void)collectCard
{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:self.collectCardModel.communityId forKey:@"communityId"];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    [postDict setValue:self.CardModel.roomId forKey:@"roomId"];
    [postDict setValue:self.collectCardModel.roomName forKey:@"name"];
    if (currentIndex != 10) {
         [postDict setValue:[NSString stringWithFormat:@"%ld",(long)currentIndex] forKey:@"index"];
    }
    __weak GenerateQRCardController * weakSelf = self;
    [cardProcess addCollectionCard:postDict file:nil block:^(NSString *info, NSString *errorInfo) {
        if (info) {
            [PromptInfoView showMessage:info superView:weakSelf.view];
            imageArray = @[@"cardShare",@"cardCollect",@"cardRefresh"];
            imageTitleArray = @[NSLocalizedString(@"cardShare", nil),NSLocalizedString(@"cancelCollect", nil),NSLocalizedString(@"cardRefresh", nil)];
            cardIsCollect = YES;
            [weakSelf checkCardIsCollect];
            [weakSelf.backTableView reloadData];
        }
        else
        {
            [PromptInfoView showMessage:errorInfo superView:weakSelf.view];
        }
    }];
}

#pragma mark - 取消收藏房卡
-(void)cancelCollectCard
{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:self.collectCardModel.communityId forKey:@"communityId"];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    [postDict setValue:self.collectCardModel.roomId forKey:@"roomId"];
     __weak GenerateQRCardController * weakSelf = self;
    [cardProcess cancelCollectionCard:postDict block:^(NSString *info, NSString *errorInfo) {
        if (info) {
            [PromptInfoView showMessage:info superView:weakSelf.view];
            imageArray = @[@"cardShare",@"unCardCollect",@"cardRefresh"];
            imageTitleArray = @[NSLocalizedString(@"cardShare", nil),NSLocalizedString(@"cardCollect", nil),NSLocalizedString(@"cardRefresh", nil)];
            cardIsCollect = NO;
            [weakSelf.backTableView reloadData];
        }
        else
        {
            [PromptInfoView showMessage:errorInfo superView:weakSelf.view];
        }
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
